package com.zlzlib.libui.util;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

/**
 * @Desc: toast 的工具类
 * @Copyright:
 * @DateTime: 2020/7/14 16:20
 * @Author zlz
 * @Version 1.0
 */
public class ToastUtil {

    private volatile static ToastUtil instance = null;

    public static ToastUtil getInstance() {
        if (instance == null) {
            synchronized (ToastUtil.class) {
                if (instance == null) {
                    instance = new ToastUtil();
                }
            }
        }
        return instance;
    }

    private ToastUtil() {

    }

    private Toast toastNormal;
    private Toast toastSelf;

    //====重复创建的toast====
    public void showShort(Context context, String text) {
        showToast(context, text, Toast.LENGTH_SHORT);
    }

    public void showLong(Context context, String text) {
        showToast(context, text, Toast.LENGTH_LONG);
    }

    public void showToast(Context context, String text, int time) {
        Toast.makeText(context, text, time).show();
    }

    //====不重复创建的toast====
    public void showShortOld(Context context, String text) {
        showOldToast(context, text, Toast.LENGTH_SHORT);
    }

    public void showLongOld(Context context, String text) {
        showOldToast(context, text, Toast.LENGTH_LONG);
    }

    public void showOldToast(Context context, String text, int time) {
        if (toastNormal == null) {
            toastNormal = Toast.makeText(context, "", time);
        }
        toastNormal.setDuration(time);
        toastNormal.setText(text);
        toastNormal.show();
    }

    public View showSelfToast(Context context, int id, int time) {
        return showSelfToast(context, id, time, false);
    }

    public View showSelfOldToast(Context context, int id, int time) {
        return showSelfToast(context, id, time, true);
    }

    /**
     * 自定义布局的toast
     *
     * @param id    布局文件id
     * @param time  时间
     * @param isOld 是否不重新创建
     */
    private View showSelfToast(Context context, int id, int time, boolean isOld) {
        if (toastSelf == null || !isOld) {
            toastSelf = new Toast(context);
        }
        LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflate.inflate(id, null);
        toastSelf.setView(v);
        toastSelf.setDuration(time);
        toastSelf.show();
        return v;
    }
}